package cn.chiship.framework.upms.biz.user.service.impl;

import cn.chiship.framework.common.constants.SystemConfigConstants;
import cn.chiship.framework.common.enums.LoginTypeEnum;
import cn.chiship.framework.common.pojo.vo.ConfigJson;
import cn.chiship.framework.common.service.GlobalCacheService;
import cn.chiship.framework.common.util.FrameworkUtil2;
import cn.chiship.framework.upms.biz.base.service.impl.AsyncMessageNotificationService;
import cn.chiship.framework.upms.biz.system.pojo.dto.UpmsNoticeSystemDto;
import cn.chiship.framework.upms.biz.system.service.UpmsDataDictService;
import cn.chiship.framework.upms.biz.system.service.UpmsNoticeService;
import cn.chiship.framework.upms.biz.system.service.UpmsRegionService;
import cn.chiship.framework.upms.biz.user.entity.*;
import cn.chiship.framework.upms.biz.user.mapper.*;
import cn.chiship.framework.upms.biz.user.pojo.dto.UpmsUserDto;
import cn.chiship.framework.upms.biz.user.pojo.dto.UpmsUserOrganizationDto;
import cn.chiship.framework.upms.biz.user.pojo.dto.UpmsUserPersonalInformationModifyDto;
import cn.chiship.framework.upms.biz.user.pojo.vo.UpmsOrganizationUserVo;
import cn.chiship.framework.upms.biz.user.pojo.vo.UpmsUserVo;
import cn.chiship.framework.upms.biz.user.service.*;
import cn.chiship.framework.upms.core.enums.NoticeModuleTypeEnums;
import cn.chiship.framework.upms.core.enums.NoticePriorityEnums;
import cn.chiship.framework.upms.core.enums.NoticeScopeEnums;
import cn.chiship.sdk.cache.util.JwtUtil;
import cn.chiship.sdk.cache.vo.CacheDepartmentVo;

import cn.chiship.sdk.cache.service.UserCacheService;
import cn.chiship.sdk.cache.vo.CacheOrganizationVo;
import cn.chiship.sdk.cache.vo.CacheRoleVo;
import cn.chiship.sdk.cache.vo.CacheUserVO;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.base.constants.RegexConstants;
import cn.chiship.sdk.core.encryption.Md5Util;
import cn.chiship.sdk.core.enums.BaseResultEnum;
import cn.chiship.sdk.core.enums.UserTypeEnum;
import cn.chiship.sdk.core.exception.ExceptionUtil;
import cn.chiship.sdk.core.id.SnowflakeIdUtil;
import cn.chiship.sdk.core.util.*;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.sdk.framework.pojo.dto.UserForgotPasswordDto;
import cn.chiship.sdk.framework.pojo.dto.UserModifyPasswordDto;
import cn.chiship.sdk.framework.pojo.vo.PageVo;
import cn.chiship.sdk.third.core.common.ThirdOauthChannelEnum;
import cn.chiship.sdk.third.core.common.ThirdOauthLoginDto;
import cn.chiship.sdk.third.core.dingtalk.vo.DingTalkBaseUserInfoVo;
import cn.chiship.sdk.third.core.dingtalk.vo.DingTalkConnectUserInfoVo;
import cn.chiship.sdk.third.core.dingtalk.vo.DingTalkUserAccessTokenVo;
import cn.chiship.sdk.third.properties.ChishipDingTalkProperties;
import cn.chiship.sdk.third.service.DingTalkService;
import cn.chiship.sdk.third.service.WxWorkService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户业务接口实现层 2021/9/27
 *
 * @author lijian
 */
@Service
public class UpmsUserServiceImpl extends BaseServiceImpl<UpmsUser, UpmsUserExample> implements UpmsUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsUserServiceImpl.class);

    @Resource
    UpmsUserMapper upmsUserMapper;

    @Resource
    UpmsRoleMapper upmsRoleMapper;

    @Resource
    UpmsOrganizationService upmsOrganizationService;

    @Resource
    UpmsUserOrganizationService upmsUserOrganizationService;

    @Resource
    UpmsUserRoleMapper upmsUserRoleMapper;

    @Resource
    UpmsUserLoginHistoryService upmsUserLoginHistoryService;

    @Resource
    private UpmsPermissionApiMapper upmsPermissionApiMapper;

    @Resource
    private UpmsUserOnlineService upmsUserOnlineService;

    @Resource
    GlobalCacheService globalCacheService;

    @Resource
    UpmsRegionService upmsRegionService;

    @Resource
    UpmsDataDictService upmsDataDictService;

    @Resource
    UserCacheService userCacheService;

    @Resource
    AsyncMessageNotificationService asyncMessageNotificationService;

    @Resource
    UpmsNoticeService upmsNoticeService;

    @Resource
    DingTalkService dingTalkService;
    @Resource
    WxWorkService wxWorkService;

    @Resource
    ChishipDingTalkProperties chishipDingTalkProperties;

    @Override
    public BaseResult page(PageVo pageVo) {
        List<UpmsUser> users = pageVo.getRecords();
        List<JSONObject> records = new ArrayList<>();
        users.forEach(user -> {
            JSONObject json = JSON.parseObject(JSON.toJSONString(user));
            records.add(json);
        });
        for (JSONObject user : records) {
            user.put("organizations", upmsUserOrganizationService.selectUserOrg(user.getString("id")));
        }
        pageVo.setRecords(records);
        return BaseResult.ok(pageVo);
    }

    @Override
    public BaseResult page(PageVo pageVo, HashMap<String, Object> paramsMap) {
        if (paramsMap.containsKey("orgId") && ObjectUtil.isNotEmpty(paramsMap.get("orgId"))) {
            String treeNumber = upmsOrganizationService.cacheGetTreeNumberById(paramsMap.get("orgId").toString());
            if (StringUtil.isNullOrEmpty(treeNumber)) {
                treeNumber = "-1";
            }
            paramsMap.put("treeNumber", treeNumber);
        }
        if (!paramsMap.containsKey("includeChildren")) {
            paramsMap.put("includeChildren", false);
        }

        Page pageResult = PageMethod.startPage(pageVo.getCurrent().intValue(), pageVo.getSize().intValue());
        List<UpmsUserVo> userVos = upmsUserMapper.selectUserAndOrgAndRole(paramsMap);
        pageVo.setRecords(assembleUserAndOrgAndRole(userVos));
        pageVo.setTotal(pageResult.getTotal());
        pageVo.setPages(Long.valueOf(pageResult.getPages()));
        return BaseResult.ok(pageVo);
    }

    public List<UpmsUserVo> assembleUserAndOrgAndRole(List<UpmsUserVo> userVos) {
        userVos.forEach(userVo -> {
            userVo.setCategory(upmsDataDictService.getDictItemNameFromCache("userCategory", userVo.getCategory()));
            if (!StringUtil.isNullOrEmpty(userVo.getUserOrgId())) {
                String[] addTimes = userVo.getAddTime().split("，");
                String[] userOrgIds = userVo.getUserOrgId().split("，");
                String[] userOrgJobs = userVo.getUserOrgJob().split("，");
                String[] userOrgPhones = userVo.getUserOrgPhone().split("，");
                String[] userOrgOrders = userVo.getUserOrgOrder().split("，");
                String[] orgIds = userVo.getOrganizationId().split("，");
                String[] orgNames = userVo.getOrganizationName().split("，");
                String[] orgCodes = userVo.getOrganizationCode().split("，");
                String[] orgTypes = userVo.getOrganizationType().split("，");

                String[] treeNumbers = userVo.getTreeNumber().split("，");
                List<JSONObject> userOrgJsons = new ArrayList<>();
                for (int i = 0; i < userOrgIds.length; i++) {
                    JSONObject userOrgJson = new JSONObject();
                    userOrgJson.put("userOrgId", userOrgIds[i]);
                    userOrgJson.put("addTime", Long.valueOf(addTimes[i]));
                    String userOrgJob = userOrgJobs[i];
                    String userOrgPhone = userOrgPhones[i];
                    String userOrgOrder = userOrgOrders[i];
                    if (StringUtil.isNullOrEmpty(userOrgJob) || "-".equals(userOrgJob)) {
                        userOrgJob = null;
                    }
                    if (StringUtil.isNullOrEmpty(userOrgPhone) || "-".equals(userOrgPhone)) {
                        userOrgPhone = null;
                    }
                    if (StringUtil.isNullOrEmpty(userOrgOrder) || "-".equals(userOrgOrder)) {
                        userOrgOrder = null;
                    }
                    userOrgJson.put("userOrgJob", userOrgJob);
                    userOrgJson.put("userOrgPhone", userOrgPhone);
                    userOrgJson.put("userOrgOrder", userOrgOrder);
                    userOrgJson.put("organizationId", orgIds[i]);
                    userOrgJson.put("organizationName", orgNames[i]);
                    userOrgJson.put("organizationType", Byte.valueOf(orgTypes[i]));
                    userOrgJson.put("organizationCode", orgCodes[i]);

                    userOrgJson.put("treeNumber", treeNumbers[i]);

                    upmsUserOrganizationService.getParentInfoByTreeNumber(treeNumbers[i], userOrgJson);
                    userOrgJsons.add(userOrgJson);
                }
                userVo.setOrganizationUsers(userOrgJsons);

            }

            List<UpmsRole> upmsRoles = new ArrayList<>();
            if (!StringUtil.isNullOrEmpty(userVo.getRoleCode())) {
                String[] roleCodes = userVo.getRoleCode().split("，");
                String[] roleNames = userVo.getRoleName().split("，");
                for (int i = 0; i < roleCodes.length; i++) {
                    UpmsRole upmsRole = new UpmsRole();
                    upmsRole.setCode(roleCodes[i]);
                    upmsRole.setName(roleNames[i]);
                    upmsRoles.add(upmsRole);
                }
            }
            userVo.setRoles(upmsRoles);

        });
        return userVos;

    }

    @Override
    public JSONObject assembleData(UpmsUser upmsUser) {
        JSONObject userJson = JSON.parseObject(JSON.toJSONString(upmsUser));
        userJson.put("_category", upmsDataDictService.getDictItemNameFromCache("userCategory", upmsUser.getCategory()));
        userJson.put("_gender", upmsDataDictService.getDictItemNameFromCache("sex", upmsUser.getGender().toString()));
        userJson.put("_education", upmsDataDictService.getDictItemNameFromCache("education", upmsUser.getEducation()));
        userJson.put("_politicalOutlook", upmsDataDictService.getDictItemNameFromCache("political", upmsUser.getPoliticalOutlook()));
        userJson.put("_educationDegree", upmsDataDictService.getDictItemNameFromCache("educatio", upmsUser.getEducationDegree()));
        userJson.put("_maritalStatus", upmsDataDictService.getDictItemNameFromCache("marital", upmsUser.getMaritalStatus()));
        userJson.put("_major", upmsDataDictService.getDictItemNameFromCache("major", upmsUser.getMajor()));
        userJson.put("_nation", upmsDataDictService.getDictItemNameFromCache("nation", upmsUser.getNation()));
        userJson.put("_currentResidenceLevel1", upmsRegionService.getCacheRegionNameById(upmsUser.getCurrentResidenceLevel1()));
        userJson.put("_currentResidenceLevel2", upmsRegionService.getCacheRegionNameById(upmsUser.getCurrentResidenceLevel2()));
        userJson.put("_currentResidenceLevel3", upmsRegionService.getCacheRegionNameById(upmsUser.getCurrentResidenceLevel3()));
        userJson.put("_currentResidenceLevel4", upmsRegionService.getCacheRegionNameById(upmsUser.getCurrentResidenceLevel4()));
        userJson.put("_nativePlaceLevel1", upmsRegionService.getCacheRegionNameById(upmsUser.getNativePlaceLevel1()));
        userJson.put("_nativePlaceLevel2", upmsRegionService.getCacheRegionNameById(upmsUser.getNativePlaceLevel2()));
        userJson.put("_nativePlaceLevel3", upmsRegionService.getCacheRegionNameById(upmsUser.getNativePlaceLevel3()));

        List<String> skills = new ArrayList<>();
        if (!StringUtil.isNullOrEmpty(upmsUser.getSkill())) {
            for (String skill : upmsUser.getSkill().split(",")) {
                skills.add(upmsDataDictService.getDictItemNameFromCache("skill", skill));
            }
        }
        userJson.put("_skill", StringUtil.join(skills, "、"));
        return userJson;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult saveUser(UpmsUserDto upmsUserDto) {
        UpmsUser upmsUser = new UpmsUser();
        BeanUtils.copyProperties(upmsUserDto, upmsUser);
        ConfigJson configJson = globalCacheService.getSystemConfigJson(Arrays.asList(SystemConfigConstants.INIT_PASSWORD));
        String initPassword = configJson.getString(SystemConfigConstants.INIT_PASSWORD);
        upmsUser.setId(SnowflakeIdUtil.generateStrId());
        upmsUser.setPassword(initPassword);
        upmsUser.setIsInitPassword(BaseConstants.YES);
        upmsUser.setIsLocked(BaseConstants.NO);
        upmsUser.setUserPinyin(ChineseCharToEn.getPinYinAll(upmsUser.getRealName()));
        upmsUser.setSalt(RandomUtil.uuidLowerCase());
        upmsUser.setPassword(Md5Util.md5(upmsUser.getPassword() + upmsUser.getSalt()));

        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andUserNameEqualTo(upmsUser.getUserName());
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (!users.isEmpty()) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_REPEAT, "用户名已存在,请重新输入");
        }
        super.insertSelective(upmsUser);
        configCompany(upmsUserDto.getUserOrganization(), upmsUser.getId());
        configRole(upmsUserDto.getRoles(), upmsUser.getId());
        return BaseResult.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult updateUser(String userId, UpmsUserDto upmsUserDto) {
        UpmsUser upmsUser = new UpmsUser();
        BeanUtils.copyProperties(upmsUserDto, upmsUser);
        upmsUser.setId(userId);
        upmsUser.setGmtModified(System.currentTimeMillis());
        upmsUser.setPassword(null);
        upmsUser.setSalt(null);
        upmsUser.setUserPinyin(ChineseCharToEn.getAllFirstLetters(upmsUser.getRealName()));

        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andUserNameEqualTo(upmsUser.getUserName()).andIdNotEqualTo(upmsUser.getId());
        List<UpmsUser> upmsUsers = upmsUserMapper.selectByExample(upmsUserExample);
        if (!upmsUsers.isEmpty()) {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_REPEAT, "用户名已存在,请重新输入");
        }

        super.updateByPrimaryKeySelective(upmsUser);
        configCompany(upmsUserDto.getUserOrganization(), upmsUser.getId());
        configRole(upmsUserDto.getRoles(), upmsUser.getId());

        return BaseResult.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult removeUser(List<String> userIds) {
        if (userIds.isEmpty()) {
            return BaseResult.error("集合不能为空");
        }
        // 删除用户
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andIdIn(userIds);
        super.deleteByExample(upmsUserExample);

        // 删除角色
        UpmsUserRoleExample upmsUserRoleExample = new UpmsUserRoleExample();
        upmsUserRoleExample.createCriteria().andUserIdIn(userIds);
        upmsUserRoleMapper.deleteByExample(upmsUserRoleExample);

        // 删除组织
        UpmsUserOrganizationExample upmsUserOrganizationExample = new UpmsUserOrganizationExample();
        upmsUserOrganizationExample.createCriteria().andUserIdIn(userIds);
        upmsUserOrganizationService.deleteByExample(upmsUserOrganizationExample);
        return BaseResult.ok();
    }

    @Override
    public BaseResult validateExistByField(String id, String field, String value) {
        boolean flag = true;
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        UpmsUserExample.Criteria criteria = upmsUserExample.createCriteria();
        if (!StringUtil.isNullOrEmpty(id)) {
            criteria.andIdNotEqualTo(id);
        }
        switch (field) {
            case "userName":
                criteria.andUserNameEqualTo(value);
                break;
            case "userCode":
                criteria.andUserCodeEqualTo(value);
                break;
            case "mobile":
                criteria.andMobileEqualTo(value);
                break;
            case "idNumber":
                criteria.andIdNumberEqualTo(value);
                break;
            default:
                flag = false;
        }
        if (flag) {
            return BaseResult.ok(upmsUserMapper.countByExample(upmsUserExample) > 0);
        } else {
            return BaseResult.error(BaseResultEnum.FAILED, "暂未配置对字段" + field + "的校验");
        }
    }

    @Override
    public BaseResult selectDetailsByPrimaryKey(Object id) {
        if (ObjectUtils.isEmpty(id)) {
            return BaseResult.error("用户主键不能为空！");
        }
        UpmsUser upmsUser = upmsUserMapper.selectByPrimaryKey(id);
        HashMap<String, Object> paramsMap = new HashMap<>(2);
        paramsMap.put("user", assembleData(upmsUser));
        paramsMap.put("roles", upmsPermissionApiMapper.selectRoleByUserId(upmsUser.getId()));
        paramsMap.put("organizations", upmsUserOrganizationService.selectUserOrg(upmsUser.getId()));
        return BaseResult.ok(paramsMap);
    }

    @Override
    public BaseResult getUserByMobile(String mobile) {
        if (!mobile.matches(RegexConstants.MOBILE)) {
            return BaseResult.error("请输入正确的手机号码!");
        }
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andMobileEqualTo(mobile);
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (users.isEmpty()) {
            return BaseResult.ok();
        }
        HashMap<String, Object> paramsMap = new HashMap(2);
        UpmsUser user = users.get(0);
        paramsMap.put("user", assembleData(user));
        paramsMap.put("roles", upmsPermissionApiMapper.selectRoleByUserId(user.getId()));
        paramsMap.put("organizations", upmsUserOrganizationService.selectUserOrg(user.getId()));
        return BaseResult.ok(paramsMap);
    }

    @Override
    public BaseResult login(String sessionId, String username, String password, String loginIp, LoginTypeEnum loginTypeEnum) {
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andIsDeletedEqualTo(BaseConstants.NO).andUserNameEqualTo(username);
        upmsUserExample.or(upmsUserExample.createCriteria().andMobileEqualTo(username).andIsDeletedEqualTo(BaseConstants.NO));
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (users.isEmpty()) {
            upmsUserLoginHistoryService.loginHistory(null, username, null, BaseResultEnum.USER_IS_EXIST_NO.getMessage(), BaseConstants.NO, loginIp, loginTypeEnum);
            return BaseResult.error(BaseResultEnum.USER_IS_EXIST_NO, null);
        }
        UpmsUser user = users.get(0);
        if (!Md5Util.md5(password + user.getSalt()).equals(user.getPassword())) {
            upmsUserLoginHistoryService.loginHistory(null, username, null, BaseResultEnum.ERROR_PASSWORD.getMessage(), BaseConstants.NO, loginIp, loginTypeEnum);
            return BaseResult.error(BaseResultEnum.ERROR_PASSWORD, null);
        }
        return login(user, loginIp, sessionId, loginTypeEnum);
    }

    @Override
    public BaseResult mobileLogin(String sessionId, String mobile, String loginIp, LoginTypeEnum loginTypeEnum) {
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andIsDeletedEqualTo(BaseConstants.NO).andMobileEqualTo(mobile);
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (users.isEmpty()) {
            upmsUserLoginHistoryService.loginHistory(null, mobile, null, BaseResultEnum.USER_IS_EXIST_NO.getMessage(), BaseConstants.NO, loginIp, loginTypeEnum);
            return BaseResult.error(BaseResultEnum.USER_IS_EXIST_NO, null);
        }
        UpmsUser user = users.get(0);
        return login(user, loginIp, sessionId, loginTypeEnum);
    }

    @Override
    public BaseResult dingTalkAuthCodeLogin(String sessionId, String authCode, String ip, LoginTypeEnum loginTypeEnum) {
        dingTalkService.config().token();
        BaseResult baseResult = dingTalkService.getBaseUserByAuthCode(authCode);
        if (!baseResult.isSuccess()) {
            return baseResult;
        }
        DingTalkBaseUserInfoVo baseUserInfoVo = (DingTalkBaseUserInfoVo) baseResult.getData();
        String userId = baseUserInfoVo.getUserId();
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andDingTalkUserIdEqualTo(userId);
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        UpmsUser user;
        if (!users.isEmpty()) {
            user = users.get(0);
        } else {
            //根据dingTalkUserId没有查到数据，说明还未绑定
            baseResult = dingTalkService.getUserById(userId);
            JSONObject json = (JSONObject) baseResult.getData();
            String mobile = json.getString("mobile");
            upmsUserExample = new UpmsUserExample();
            upmsUserExample.createCriteria().andIsDeletedEqualTo(BaseConstants.NO).andMobileEqualTo(mobile);
            users = upmsUserMapper.selectByExample(upmsUserExample);
            if (users.isEmpty()) {
                upmsUserLoginHistoryService.loginHistory(null, mobile, null, BaseResultEnum.USER_IS_EXIST_NO.getMessage(), BaseConstants.NO, ip, loginTypeEnum);
                return BaseResult.error(BaseResultEnum.USER_IS_EXIST_NO, null);
            }
            user = users.get(0);
            user.setDingTalkUserId(userId);
            upmsUserMapper.updateByPrimaryKeySelective(user);
        }
        return login(user, ip, sessionId, loginTypeEnum);
    }

    @Override
    public BaseResult thirdOauth2Auth(ThirdOauthLoginDto thirdOauthLoginDto) {
        String callback = thirdOauthLoginDto.getCallback();
        callback = Base64Util.encode(callback.getBytes());
        if (callback.length() > 128) {
            return BaseResult.error("回调路径参数过长，超过128字符");
        }
        String url = null;
        if (ThirdOauthChannelEnum.OAUTH_CHANNEL_DING_TALK.equals(thirdOauthLoginDto.getOauthChannel())) {
            dingTalkService.config().token();
            url = dingTalkService.getOauth2Auth(callback);
            LOGGER.info("钉钉回调地址：" + url);
        }
        if (ThirdOauthChannelEnum.OAUTH_CHANNEL_WX_WORK_PAGE.equals(thirdOauthLoginDto.getOauthChannel())) {
            wxWorkService.config().token();
            url = wxWorkService.getWxLoginSso(callback);
            LOGGER.info("企业微信Web回调地址：" + url);
        }
        if (ThirdOauthChannelEnum.OAUTH_CHANNEL_WX_WORK_WEB.equals(thirdOauthLoginDto.getOauthChannel())) {
            wxWorkService.config().token();
            url = wxWorkService.getOauth2Auth(callback);
            LOGGER.info("企业微信网页回调地址：" + url);
        }
        if (StringUtil.isNullOrEmpty(url)) {
            return BaseResult.error("不支持的授权渠道");
        }
        return BaseResult.ok(url);
    }

    @Override
    public BaseResult dingTalkOauth2AuthLogin(String sessionId, String authCode, String ip, LoginTypeEnum loginTypeEnum) {
        dingTalkService.config().token();
        BaseResult baseResult = dingTalkService.getOauth2AccessToken(authCode, false);
        if (!baseResult.isSuccess()) {
            return baseResult;
        }
        DingTalkUserAccessTokenVo userAccessTokenVo = (DingTalkUserAccessTokenVo) baseResult.getData();
        //此地方可根据实际业务进行调整
        if (!chishipDingTalkProperties.getCorpId().equals(userAccessTokenVo.getCorpId())) {
            return BaseResult.error("所选企业无登录权限");
        }
        baseResult = dingTalkService.getUserByOauth2AccessToken(userAccessTokenVo.getAccessToken());
        if (!baseResult.isSuccess()) {
            return baseResult;
        }
        DingTalkConnectUserInfoVo connectUserInfoVo = (DingTalkConnectUserInfoVo) baseResult.getData();
        // return mobileLogin(sessionId, connectUserInfoVo.getMobile(), ip, loginTypeEnum);
        //根据自己业务，是否决定扫码就绑定userId
        baseResult = dingTalkService.getUserByMobile(connectUserInfoVo.getMobile());
        if (!baseResult.isSuccess()) {
            return baseResult;
        }
        JSONObject json = (JSONObject) baseResult.getData();
        String userId = json.getString("userid");
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andDingTalkUserIdEqualTo(userId);
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        UpmsUser user;
        if (!users.isEmpty()) {
            user = users.get(0);
        } else {
            //根据dingTalkUserId没有查到数据，说明还未绑定
            upmsUserExample = new UpmsUserExample();
            upmsUserExample.createCriteria().andIsDeletedEqualTo(BaseConstants.NO).andMobileEqualTo(connectUserInfoVo.getMobile());
            users = upmsUserMapper.selectByExample(upmsUserExample);
            if (users.isEmpty()) {
                upmsUserLoginHistoryService.loginHistory(null, connectUserInfoVo.getMobile(), null, BaseResultEnum.USER_IS_EXIST_NO.getMessage(), BaseConstants.NO, ip, loginTypeEnum);
                return BaseResult.error(BaseResultEnum.USER_IS_EXIST_NO, null);
            }
            user = users.get(0);
            user.setDingTalkUserId(userId);
            upmsUserMapper.updateByPrimaryKeySelective(user);
        }
        return login(user, ip, sessionId, loginTypeEnum);
    }

    @Override
    public BaseResult wxWorkOauth2AuthLogin(String sessionId, String authCode, String ip, LoginTypeEnum loginTypeEnum) {
        BaseResult baseResult = wxWorkService.getUserIdByAuthCode(authCode);
        if (!baseResult.isSuccess()) {
            return baseResult;
        }
        String wxWorkUserId = baseResult.getData().toString();
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andWxWorkUserIdEqualTo(wxWorkUserId);
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (users.isEmpty()) {
            return BaseResult.error("系统还未绑定授权账号【" + wxWorkUserId + "】，请将账号发给管理员进行绑定");
        }
        UpmsUser user = users.get(0);
        return login(user, ip, sessionId, loginTypeEnum);
    }

    @Override
    public BaseResult scanLogin(String sessionId, String username, String loginIp, LoginTypeEnum loginTypeEnum) {
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andIsDeletedEqualTo(BaseConstants.NO).andUserNameEqualTo(username);
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (users.isEmpty()) {
            upmsUserLoginHistoryService.loginHistory(null, username, null, BaseResultEnum.USER_IS_EXIST_NO.getMessage(), BaseConstants.NO, loginIp, loginTypeEnum);
            return BaseResult.error(BaseResultEnum.USER_IS_EXIST_NO, null);
        }
        UpmsUser user = users.get(0);

        return login(user, loginIp, sessionId, loginTypeEnum);
    }

    private BaseResult login(UpmsUser user, String loginIp, String sessionId, LoginTypeEnum loginTypeEnum) {
        try {
            if (BaseConstants.YES == user.getIsLocked()) {
                upmsUserLoginHistoryService.loginHistory(null, user.getUserName(), null, BaseResultEnum.ACCOUNT_LOCKED.getMessage(), BaseConstants.NO, loginIp, loginTypeEnum);
                return BaseResult.error(BaseResultEnum.ACCOUNT_LOCKED, null);
            }

            CacheUserVO userVO = new CacheUserVO(UserTypeEnum.ADMIN);
            /**
             * 用户基本信息
             */
            userVO.setMobile(user.getMobile());
            userVO.setEmail(user.getEmail());
            userVO.setUsername(user.getUserName());
            userVO.setId(user.getId());
            userVO.setRealName(user.getRealName());
            userVO.setStatus(user.getIsLocked());
            userVO.setAvatar(user.getAvatar());
            userVO.setInitPassword(user.getIsInitPassword() != 0);
            userVO.setUserCode(user.getUserCode());
            userVO.setSessionId(sessionId);

            // 用户组织信息
            userVO = setLoginUserOrganization(userVO, null);

            /**
             * 用户菜单与权限
             */
            List<String> perms = new ArrayList<>();
            List<Object> menuPerms = new ArrayList<>();
            List<UpmsPermission> permissions = upmsPermissionApiMapper.selectPermissionByUserId(user.getId());
            for (UpmsPermission permission : permissions) {
                if (2 == permission.getType()) {
                    perms.add(permission.getPermissionValue());
                } else {
                    JSONObject json = new JSONObject();
                    json.put("title", permission.getName());
                    json.put("code", permission.getPermissionValue());
                    json.put("icon", permission.getIcon());
                    json.put("orders", permission.getOrders());
                    menuPerms.add(json);
                }
            }
            userVO.setPerms(perms);
            userVO.setMenuPerms(menuPerms);

            /**
             * 用户角色
             */
            List<UpmsRole> upmsRoles = upmsPermissionApiMapper.selectRoleByUserId(user.getId());
            List<CacheRoleVo> roleVos = new ArrayList<>();
            for (UpmsRole upmsRole : upmsRoles) {
                CacheRoleVo roleVo = new CacheRoleVo();
                roleVo.setRoleCode(upmsRole.getCode());
                roleVo.setRoleName(upmsRole.getName());
                roleVo.setDataScope(upmsRole.getDataScope());
                roleVos.add(roleVo);
            }
            userVO.setCacheRoleVos(roleVos);

            /**
             * 更新操作
             */
            if (!StringUtil.isNullOrEmpty(user.getLastLoginIp())) {
                user.setPrevLoginIp(user.getLastLoginIp());
            }
            if (!StringUtil.isNull(user.getLastLoginDate())) {
                user.setPrevLoginDate(user.getLastLoginDate());
            }
            user.setLastLoginDate(System.currentTimeMillis());
            user.setLastLoginIp(loginIp);
            Integer loginNum = 0;
            if (!StringUtil.isNull(user.getLoginNum())) {
                loginNum = user.getLoginNum();
            }
            user.setLoginNum(loginNum + 1);
            upmsUserMapper.updateByPrimaryKeySelective(user);
            Map<String, Object> extInfo = new HashMap<>(7);
            extInfo.put("preLoginIp", user.getPrevLoginIp());
            extInfo.put("preLoginDate", user.getPrevLoginDate());
            extInfo.put("lastLoginIp", user.getLastLoginIp());
            extInfo.put("lastLoginDate", user.getLastLoginDate());
            extInfo.put("loginNums", user.getLoginNum());
            userVO.setExtInfo(extInfo);

            String accessToken = JwtUtil.createToken(userVO);
            upmsUserLoginHistoryService.loginHistory(userVO.getId(), user.getUserName(), userVO.getRealName(), "登录成功", BaseConstants.YES, loginIp, loginTypeEnum);
            upmsUserOnlineService.loginUserToUserOnline(accessToken, userVO, loginIp);
            userCacheService.cacheUser(accessToken, userVO);

            return BaseResult.ok(accessToken);
        } catch (Exception e) {
            return ExceptionUtil.formatException(e);
        }

    }

    private CacheUserVO setLoginUserOrganization(CacheUserVO userVO, String orgId) {
        List<UpmsOrganizationUserVo> organizations = upmsPermissionApiMapper.selectOrganizationByUserId(userVO.getId());
        if (!organizations.isEmpty()) {
            UpmsOrganization upmsOrganization;
            if (StringUtil.isNullOrEmpty(orgId)) {
                upmsOrganization = organizations.get(0);
            } else {
                List<UpmsOrganization> temp = organizations.stream().filter(unit -> unit.getId().equals(orgId)).collect(Collectors.toList());
                if (temp.isEmpty()) {
                    return userVO;
                } else {
                    upmsOrganization = temp.get(0);
                }
            }
            userVO.setCacheOrganizationVo(analyticalAssemblyOrganization(upmsOrganization));
            /**
             * 机构
             */
            List<CacheOrganizationVo> cacheOrganizationVos = new ArrayList<>();
            for (UpmsOrganization organization : organizations) {
                cacheOrganizationVos.add(analyticalAssemblyOrganization(organization));
            }
            userVO.setCacheOrganizationVos(cacheOrganizationVos);
        } else {
            userVO.setCacheOrganizationVo(null);
            userVO.setCacheOrganizationVos(null);
        }
        return userVO;
    }

    private CacheOrganizationVo analyticalAssemblyOrganization(UpmsOrganization upmsOrganization) {
        if (ObjectUtils.isEmpty(upmsOrganization)) {
            return new CacheOrganizationVo();
        }
        String[] regions = new String[4];
        regions[0] = upmsRegionService.getCacheRegionNameById(upmsOrganization.getRegionLevel1());
        regions[1] = upmsRegionService.getCacheRegionNameById(upmsOrganization.getRegionLevel2());
        regions[2] = upmsRegionService.getCacheRegionNameById(upmsOrganization.getRegionLevel3());
        regions[3] = upmsRegionService.getCacheRegionNameById(upmsOrganization.getRegionLevel4());
        return new CacheOrganizationVo(upmsOrganization.getId(), upmsOrganization.getPid(), upmsOrganization.getOrganizationCode(), Byte.valueOf("1").equals(upmsOrganization.getType()) ? upmsOrganization.getOrganizationName() : upmsUserOrganizationService.getParentOrgNameByTreeNumber(upmsOrganization.getTreeNumber()), upmsOrganization.getType(), upmsOrganization.getOrganizationLevel(), upmsOrganization.getOrganizationCategory(), upmsOrganization.getOrganizationTag(), upmsOrganization.getTreeNumber(), upmsOrganization.getLogo(), upmsOrganization.getChargeInfo(), upmsOrganization.getRegionLevel1(), upmsOrganization.getRegionLevel2(), upmsOrganization.getRegionLevel3(), upmsOrganization.getRegionLevel4(), StringUtil.join(regions), null);
    }

    private CacheDepartmentVo analyticalAssemblyDepartment(UpmsOrganization upmsOrganization) {

        return new CacheDepartmentVo(upmsOrganization.getId(), upmsOrganization.getOrganizationCode(), upmsOrganization.getOrganizationName(), upmsOrganization.getLogo(), upmsOrganization.getTreeNumber());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult register(String mobile, String realName, String password, String passwordAgain) {
        ConfigJson configJson = globalCacheService.getSystemConfigJson(Arrays.asList(SystemConfigConstants.DEFAULT_ROLE));
        String defaultRole = configJson.getString(SystemConfigConstants.DEFAULT_ROLE);
        if (!password.equals(passwordAgain)) {
            return BaseResult.error("确认密码输入错误！");
        }
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andMobileEqualTo(mobile);
        if (upmsUserMapper.countByExample(upmsUserExample) > 0) {
            return BaseResult.error("输入的手机号不存在,请重新输入！");
        }
        UpmsRoleExample upmsRoleExample = new UpmsRoleExample();
        upmsRoleExample.createCriteria().andCodeEqualTo(defaultRole);
        List<UpmsRole> roles = upmsRoleMapper.selectByExample(upmsRoleExample);
        if (roles.isEmpty()) {
            return BaseResult.error("系统缺少【" + defaultRole + "】角色，暂无法注册用户！");
        }

        UpmsUser upmsUser = new UpmsUser();
        upmsUser.setSalt(RandomUtil.uuidLowerCase());
        upmsUser.setPassword(Md5Util.md5(password + upmsUser.getSalt()));
        upmsUser.setMobile(mobile);
        upmsUser.setUserName(mobile);
        upmsUser.setRealName(realName);
        upmsUser.setIsInitPassword(Byte.valueOf("0"));
        upmsUser.setUserCode(RandomUtil.getString(7));
        upmsUser.setUserPinyin(ChineseCharToEn.getAllFirstLetters(realName));
        super.insertSelective(upmsUser);

        configRole(StringUtil.strToListString(roles.get(0).getId(), ","), upmsUser.getId());
        return BaseResult.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult joinOrg(CacheUserVO cacheUserVO, String invitationCode, String realName) {
        if (!cacheUserVO.getRealName().equals(realName)) {
            return BaseResult.error("真实姓名与登录账号信息不符，请重新输入！");
        }
        String userId = StringUtil.getString(cacheUserVO.getId());
        Long organizationId;
        try {
            organizationId = ShareCodeUtil.codeToId(invitationCode);
        } catch (Exception e) {
            return BaseResult.error("无效的邀请码！");
        }
        UpmsOrganization organization = upmsOrganizationService.selectByPrimaryKey(StringUtil.getString(organizationId));
        if (StringUtil.isNull(organization)) {
            return BaseResult.error("无效的邀请码！");
        }
        UpmsUserOrganizationExample upmsUserOrganizationExample = new UpmsUserOrganizationExample();
        upmsUserOrganizationExample.createCriteria().andUserIdEqualTo(userId).andOrganizationIdEqualTo(StringUtil.getString(organizationId));
        if (upmsUserOrganizationService.countByExample(upmsUserOrganizationExample) > 0) {
            return BaseResult.error("您已经加入该组织，无需再次加入！");
        }
        UpmsUserOrganizationDto upmsUserOrganizationDto = new UpmsUserOrganizationDto();
        upmsUserOrganizationDto.setUserId(userId);
        upmsUserOrganizationDto.setOrganizationId(organization.getId());
        upmsUserOrganizationDto.setOrders(1);
        upmsUserOrganizationService.saveUserOrganization(upmsUserOrganizationDto);
        cacheUserVO = setLoginUserOrganization(cacheUserVO, upmsUserOrganizationDto.getOrganizationId());
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);

        UpmsNoticeSystemDto upmsNoticeSystemDto = new UpmsNoticeSystemDto("加入组织", "您已通过邀请码成功加入到组织 " + organization.getOrganizationName(), NoticePriorityEnums.NOTICE_PRIORITY_LOW, NoticeModuleTypeEnums.NOTICE_MODULE_TYPE_DEFAULT, UserTypeEnum.ADMIN, userId, realName);
        asyncMessageNotificationService.sendSystemMsg(upmsNoticeSystemDto);
        return BaseResult.ok(accessToken);
    }

    @Override
    public BaseResult leaveOrg(CacheUserVO cacheUserVO, String organizationId) {
        UpmsOrganization organization = upmsOrganizationService.selectByPrimaryKey(organizationId);
        if (StringUtil.isNull(organization)) {
            return BaseResult.error("企业不存在！");
        }
        UpmsUserOrganizationExample upmsUserOrganizationExample = new UpmsUserOrganizationExample();
        upmsUserOrganizationExample.createCriteria().andOrganizationIdEqualTo(organizationId).andUserIdEqualTo(StringUtil.getString(cacheUserVO.getId()));
        upmsUserOrganizationService.deleteByExample(upmsUserOrganizationExample);
        cacheUserVO = setLoginUserOrganization(cacheUserVO, null);
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);
        return BaseResult.ok(accessToken);
    }

    @Override
    public BaseResult enterOrg(CacheUserVO cacheUserVO, String organizationId) {
        UpmsOrganization organization = upmsOrganizationService.selectByPrimaryKey(organizationId);
        if (StringUtil.isNull(organization)) {
            return BaseResult.error("企业不存在！");
        }
        cacheUserVO = setLoginUserOrganization(cacheUserVO, organizationId);
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);

        UpmsNoticeSystemDto upmsNoticeSystemDto = new UpmsNoticeSystemDto("切换组织", "您已成功切换进入到组织 " + organization.getOrganizationName(), NoticePriorityEnums.NOTICE_PRIORITY_LOW, NoticeModuleTypeEnums.NOTICE_MODULE_TYPE_DEFAULT, UserTypeEnum.ADMIN, cacheUserVO.getId(), cacheUserVO.getRealName());
        asyncMessageNotificationService.sendSystemMsg(upmsNoticeSystemDto);
        return BaseResult.ok(accessToken);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult dissolutionOrg(CacheUserVO cacheUserVO, String organizationId) {
        UpmsOrganization organization = upmsOrganizationService.selectByPrimaryKey(organizationId);
        if (StringUtil.isNull(organization)) {
            return BaseResult.error("企业不存在！");
        }
        if (StringUtil.isNullOrEmpty(organization.getChargeInfo())) {
            return BaseResult.error("该企业未设置负责人，不能解散，若想解散，请联系管理员！");
        }
        String[] chargeInfo = organization.getChargeInfo().split(":");
        if (chargeInfo.length != 2) {
            return BaseResult.error("企业负责人设置出现问题，请重新设置企业负责人！");
        }
        if (!cacheUserVO.getId().equals(chargeInfo[0])) {
            return BaseResult.error("您不是该企业负责人，无权解散企业，请联系企业负责人【" + chargeInfo[1] + "】");
        }
        upmsOrganizationService.dissolution(organizationId);
        cacheUserVO = setLoginUserOrganization(cacheUserVO, null);
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);
        return BaseResult.ok(accessToken);
    }

    @Override
    public BaseResult changeDept(CacheUserVO cacheUserVO, String deptId) {
        UpmsOrganization organization = upmsOrganizationService.selectByPrimaryKey(deptId);
        if (StringUtil.isNull(organization)) {
            return BaseResult.error("部门不存在！");
        }
        cacheUserVO.setCacheDepartmentVo(analyticalAssemblyDepartment(organization));
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);
        return BaseResult.ok(accessToken);
    }

    @Override
    public BaseResult checkJoinOrg(String userId, String invitationCode) {
        Long organizationId = -1L;
        try {
            organizationId = ShareCodeUtil.codeToId(invitationCode);
        } catch (Exception e) {
            return BaseResult.error("无效的邀请码！");
        }
        UpmsOrganization organization = upmsOrganizationService.selectByPrimaryKey(StringUtil.getString(organizationId));
        if (StringUtil.isNull(organization)) {
            return BaseResult.error("无效的邀请码！");
        }
        UpmsUserOrganizationExample upmsUserOrganizationExample = new UpmsUserOrganizationExample();
        upmsUserOrganizationExample.createCriteria().andUserIdEqualTo(userId).andOrganizationIdEqualTo(StringUtil.getString(organizationId));
        if (upmsUserOrganizationService.countByExample(upmsUserOrganizationExample) > 0) {
            return BaseResult.error("您已经加入该组织，无需再次加入！");
        }
        return BaseResult.ok();
    }

    @Override
    public BaseResult modifyPassword(String userId, UserModifyPasswordDto modifyPasswordDto) {
        String oldPassword = modifyPasswordDto.getOldPassword();
        String newPassword = modifyPasswordDto.getNewPassword();
        String newPasswordAgain = modifyPasswordDto.getNewPasswordAgain();
        UpmsUser upmsUser = upmsUserMapper.selectByPrimaryKey(userId);
        if (!modifyPasswordDto.getMobile().equals(upmsUser.getMobile())) {
            return BaseResult.error("手机号与登录账号手机不符");
        }
        if (oldPassword.equals(newPassword)) {
            return BaseResult.error(BaseResultEnum.ERROR_PASSWORD, "新旧密码不能一致");
        }
        if (!Md5Util.md5(oldPassword + upmsUser.getSalt()).equals(upmsUser.getPassword())) {
            return BaseResult.error(BaseResultEnum.ERROR_PASSWORD, "旧密码输入错误");
        }
        if (!newPassword.equals(newPasswordAgain)) {
            return BaseResult.error("确认密码输入错误！");
        }
        upmsUser.setSalt(RandomUtil.uuidLowerCase());
        upmsUser.setPassword(Md5Util.md5(newPassword + upmsUser.getSalt()));
        upmsUser.setGmtModified(System.currentTimeMillis());
        upmsUser.setIsInitPassword(BaseConstants.NO);
        return super.updateByPrimaryKeySelective(upmsUser);
    }

    @Override
    public BaseResult forgotPassword(UserForgotPasswordDto userForgotPasswordDto) {
        String mobile = userForgotPasswordDto.getMobile();
        String password = userForgotPasswordDto.getPassword();
        String passwordAgain = userForgotPasswordDto.getPasswordAgain();
        if (!password.equals(passwordAgain)) {
            return BaseResult.error("确认密码输入错误！");
        }
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andMobileEqualTo(mobile);
        List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
        if (users.isEmpty()) {
            return BaseResult.error("输入的手机号不存在,请重新输入！");
        }
        UpmsUser upmsUser = users.get(0);
        upmsUser.setSalt(RandomUtil.uuidLowerCase());
        upmsUser.setPassword(Md5Util.md5(password + upmsUser.getSalt()));
        upmsUser.setGmtModified(System.currentTimeMillis());
        upmsUser.setIsInitPassword(BaseConstants.NO);
        return super.updateByPrimaryKeySelective(upmsUser);
    }

    @Override
    public BaseResult modifyAvatar(String avatar, CacheUserVO cacheUserVO) {
        UpmsUser user = upmsUserMapper.selectByPrimaryKey(cacheUserVO.getId());
        if (StringUtil.isNull(user)) {
            return BaseResult.error("查无此用户！");
        }
        user.setAvatar(avatar);
        super.updateByPrimaryKeySelective(user);
        cacheUserVO.setAvatar(avatar);
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);
        return BaseResult.ok(accessToken);
    }

    @Override
    public BaseResult modifyUserName(String userName, String id) {
        UpmsUser user = upmsUserMapper.selectByPrimaryKey(id);
        if (StringUtil.isNull(user)) {
            return BaseResult.error("查无此用户！");
        }
        if (StringUtil.isNullOrEmpty(user.getUserName())) {
            user.setUserName(userName);
        } else {
            if (userName.equals(user.getUserName())) {
                return BaseResult.error("不能与原用户名一致,请重新输入！");
            } else {
                user.setUserName(userName);
            }
        }
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andUserNameEqualTo(userName).andIdNotEqualTo(id);
        if (upmsUserMapper.countByExample(upmsUserExample) > 0) {
            return BaseResult.error("用户名已存在,请重新输入！");
        }
        super.updateByPrimaryKeySelective(user);
        return BaseResult.ok();
    }

    @Override
    public BaseResult modifyEmail(String newEmail, CacheUserVO cacheUserVO) {
        if (!StringUtil.isNullOrEmpty(cacheUserVO.getEmail())) {
            if (newEmail.equals(cacheUserVO.getEmail())) {
                return BaseResult.error("新旧邮箱不能一致！");
            }
            UpmsUserExample upmsUserExample = new UpmsUserExample();
            upmsUserExample.createCriteria().andEmailEqualTo(newEmail).andIdNotEqualTo(StringUtil.getString(cacheUserVO.getId()));
            if (upmsUserMapper.countByExample(upmsUserExample) > 0) {
                return BaseResult.error("新邮箱号已被使用,请重新输入!");
            }
        }

        UpmsUser user = upmsUserMapper.selectByPrimaryKey(cacheUserVO.getId());
        if (StringUtil.isNull(user)) {
            return BaseResult.error("查无此用户！");
        }

        user.setEmail(newEmail);
        super.updateByPrimaryKeySelective(user);
        cacheUserVO.setEmail(newEmail);
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);
        return BaseResult.ok(accessToken);
    }

    @Override
    public BaseResult modifyPersonInfo(String userId, UpmsUserPersonalInformationModifyDto personalInformationModifyDto) {
        UpmsUser upmsUser = new UpmsUser();
        BeanUtils.copyProperties(personalInformationModifyDto, upmsUser);
        upmsUser.setId(userId);
        return super.updateByPrimaryKeySelective(upmsUser);
    }

    @Override
    public BaseResult modifyMobile(String newMobile, CacheUserVO cacheUserVO) {
        if (!StringUtil.isNullOrEmpty(cacheUserVO.getMobile())) {
            if (newMobile.equals(cacheUserVO.getMobile())) {
                return BaseResult.error("新旧手机号不能一致！");
            }
            UpmsUserExample upmsUserExample = new UpmsUserExample();
            upmsUserExample.createCriteria().andMobileEqualTo(newMobile).andIdNotEqualTo(StringUtil.getString(cacheUserVO.getId()));
            if (upmsUserMapper.countByExample(upmsUserExample) > 0) {
                return BaseResult.error("新手机号已被使用,请重新输入!");
            }
        }

        UpmsUser user = upmsUserMapper.selectByPrimaryKey(cacheUserVO.getId());
        if (StringUtil.isNull(user)) {
            return BaseResult.error("查无此用户！");
        }
        user.setMobile(newMobile);
        super.updateByPrimaryKeySelective(user);
        cacheUserVO.setMobile(newMobile);
        userCacheService.removeUser();
        String accessToken = JwtUtil.createToken(cacheUserVO);
        userCacheService.cacheUser(accessToken, cacheUserVO);
        return BaseResult.ok(accessToken);
    }

    @Override
    public BaseResult unlock(String userId, String password, String ip) {
        UpmsUser upmsUser = upmsUserMapper.selectByPrimaryKey(userId);
        if (!Md5Util.md5(password + upmsUser.getSalt()).equals(upmsUser.getPassword())) {
            return BaseResult.error(BaseResultEnum.ERROR_PASSWORD, "密码输入错误");
        }
        return BaseResult.ok();
    }

    @Override
    public BaseResult initialPassword(List<String> ids) {
        if (ObjectUtils.isEmpty(ids)) {
            return BaseResult.error("主键集合不能为空！");
        }
        ConfigJson configJson = globalCacheService.getSystemConfigJson(Arrays.asList(SystemConfigConstants.INIT_PASSWORD));
        String initPassword = configJson.getString(SystemConfigConstants.INIT_PASSWORD);
        UpmsUserExample upmsUserExample = new UpmsUserExample();
        upmsUserExample.createCriteria().andIdIn(ids);
        UpmsUser upmsUser = new UpmsUser();
        upmsUser.setPassword(initPassword);
        upmsUser.setSalt(RandomUtil.uuidLowerCase());
        upmsUser.setPassword(Md5Util.md5(upmsUser.getPassword() + upmsUser.getSalt()));
        upmsUser.setIsInitPassword(BaseConstants.YES);
        int i = upmsUserMapper.updateByExampleSelective(upmsUser, upmsUserExample);
        if (i == 0) {
            return BaseResult.error(BaseResultEnum.FAILED, "初始化密码失败");
        } else {
            return BaseResult.ok("初始化密码成功,密码为'" + initPassword + "'");
        }
    }

    @Override
    public BaseResult changeIsLocked(String id, Boolean isLocked) {
        UpmsUser upmsUser = upmsUserMapper.selectByPrimaryKey(id);
        upmsUser.setIsLocked(Boolean.TRUE.equals(isLocked) ? BaseConstants.YES : BaseConstants.NO);
        upmsUserMapper.updateByPrimaryKeySelective(upmsUser);
        return BaseResult.ok();
    }

    /**
     * 配置角色
     *
     * @param roleIds
     * @param userId
     */
    private void configRole(List<String> roleIds, String userId) {
        if (ObjectUtils.isEmpty(roleIds)) {
            UpmsUserRoleExample upmsUserRoleExample = new UpmsUserRoleExample();
            upmsUserRoleExample.createCriteria().andUserIdEqualTo(userId);
            upmsUserRoleMapper.deleteByExample(upmsUserRoleExample);
            return;
        }
        List<UpmsRole> upmsRoles = upmsPermissionApiMapper.selectRoleByUserId(userId);
        List<String> listUserRoleId = new ArrayList<>();
        for (UpmsRole upmsRole : upmsRoles) {
            listUserRoleId.add(upmsRole.getId());
        }
        UpmsUserRoleExample upmsUserRoleExample = new UpmsUserRoleExample();
        UpmsUserRoleExample.Criteria criteriaUserRole = upmsUserRoleExample.createCriteria().andUserIdEqualTo(userId);
        if (!StringUtil.isNull(roleIds)) {
            /**
             * 新增
             */
            List<String> notExists = new ArrayList<>(roleIds);
            notExists.removeAll(listUserRoleId);
            if (!notExists.isEmpty()) {
                List<UpmsUserRole> listUserRole = new ArrayList<>();
                for (String userRoleId : notExists) {
                    UpmsUserRole upmsUserRole = new UpmsUserRole();
                    upmsUserRole.setId(SnowflakeIdUtil.generateStrId());
                    upmsUserRole.setIsDeleted(BaseConstants.NO);
                    upmsUserRole.setGmtCreated(System.currentTimeMillis());
                    upmsUserRole.setGmtModified(System.currentTimeMillis());
                    upmsUserRole.setRoleId(userRoleId);
                    upmsUserRole.setUserId(userId);
                    listUserRole.add(upmsUserRole);
                }
                upmsUserRoleMapper.insertSelectiveBatch(listUserRole);
            }

            /**
             * 删除
             */
            List<String> currentNotExists = new ArrayList<>(listUserRoleId);
            currentNotExists.removeAll(roleIds);
            if (!currentNotExists.isEmpty()) {
                List<String> removeUserRole = new ArrayList<>();
                for (String userRoleId : currentNotExists) {
                    removeUserRole.add(userRoleId);
                }
                criteriaUserRole.andRoleIdIn(removeUserRole);
                upmsUserRoleMapper.deleteByExample(upmsUserRoleExample);
            }
        }

    }

    /**
     * 配置单位
     *
     * @param upmsUserOrganizationDto
     * @param userId
     */
    private void configCompany(UpmsUserOrganizationDto upmsUserOrganizationDto, String userId) {
        if (ObjectUtil.isEmpty(upmsUserOrganizationDto)) {
            return;
        }
        upmsUserOrganizationDto.setUserId(userId);
        upmsUserOrganizationService.saveUserOrganization(upmsUserOrganizationDto);
    }

    @Override
    public BaseResult getPermission(String userId) {
        List<UpmsPermission> permissions = upmsPermissionApiMapper.selectPermissionByUserId(userId);
        permissions.sort(new Comparator<UpmsPermission>() {
            @Override
            public int compare(UpmsPermission o1, UpmsPermission o2) {
                return o2.getOrders().compareTo(o1.getOrders());
            }
        });
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("all", permissions);

        List<UpmsPermission> pcMenus = new ArrayList<>();
        List<String> pcPerms = new ArrayList<>();

        List<UpmsPermission> h5Menus = new ArrayList<>();
        List<String> h5Perms = new ArrayList<>();
        for (UpmsPermission permission : permissions) {
            if (0 == permission.getCategory() && 1 == permission.getType()) {
                pcMenus.add(permission);
            } else if (1 == permission.getCategory() && 1 == permission.getType()) {
                h5Menus.add(permission);
            } else if (0 == permission.getCategory() && 2 == permission.getType()) {
                pcPerms.add(permission.getPermissionValue());
            } else if (1 == permission.getCategory() && 2 == permission.getType()) {
                h5Perms.add(permission.getPermissionValue());
            }
        }
        resultMap.put("pcMenus", FrameworkUtil2.assemblyDataTree("0", pcMenus));
        resultMap.put("pcPerms", pcPerms);

        resultMap.put("h5Menus", FrameworkUtil2.assemblyDataTree("0", h5Menus));
        resultMap.put("h5Perms", h5Perms);

        return BaseResult.ok(resultMap);
    }

    @Override
    public BaseResult publishNotice(String noticeId, String scope) {
        if (!Arrays.asList(NoticeScopeEnums.NOTICE_SCOPE_ALL.getType(), NoticeScopeEnums.NOTICE_SCOPE_USER.getType()).contains(scope)) {
            return BaseResult.error("接收范围不正确");
        }
        List<String> userIds = new ArrayList<>();
        if (NoticeScopeEnums.NOTICE_SCOPE_ALL.getType().equals(scope)) {
            UpmsUserExample upmsUserExample = new UpmsUserExample();
            upmsUserExample.createCriteria().andIsLockedEqualTo(BaseConstants.NO).andIsDeletedEqualTo(BaseConstants.NO);
            List<UpmsUser> users = upmsUserMapper.selectByExample(upmsUserExample);
            for (UpmsUser user : users) {
                userIds.add(user.getId());
            }
        }
        upmsNoticeService.publish(noticeId, userIds);
        return BaseResult.ok();
    }


}
